package com.cskaoyan.wordmemorize.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cskaoyan.wordmemorize.common.annotation.OperateLog;
import com.cskaoyan.wordmemorize.common.constant.ResultCodeEnum;
import com.cskaoyan.wordmemorize.common.exception.BusinessException;
import com.cskaoyan.wordmemorize.converter.GoodsConverter;
import com.cskaoyan.wordmemorize.dao.entity.GoodsDO;
import com.cskaoyan.wordmemorize.dao.mapper.GoodsMapper;
import com.cskaoyan.wordmemorize.dto.admin.DeleteGoodsOperateDTO;
import com.cskaoyan.wordmemorize.dto.admin.GoodsDTO;
import com.cskaoyan.wordmemorize.dto.admin.PageDTO;
import com.cskaoyan.wordmemorize.request.BatchDeleteCommand;
import com.cskaoyan.wordmemorize.request.GoodsCommand;
import com.cskaoyan.wordmemorize.request.GoodsPageRequest;
import com.cskaoyan.wordmemorize.request.PageRequest;
import com.cskaoyan.wordmemorize.service.GoodsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 商品服务实现类
 */
@Service
@Slf4j
public class GoodsServiceImpl extends ServiceImpl<GoodsMapper, GoodsDO> implements GoodsService {

    @Autowired
    private GoodsConverter goodsConverter;

    /**
     * 分页获取商品信息(后台商品管理)
     *
     * @param pageRequest 分页请求参数
     * @return 商品分页数据
     */
    @Override
    public PageDTO<GoodsDTO> getGoodsPage(PageRequest pageRequest) {
        // 构建分页对象的默认参数，默认从第一页开始，每页显示10条记录
        int pageNum = pageRequest.getPageNum() != null ? pageRequest.getPageNum() : 1;
        int count = pageRequest.getCount() != null ? pageRequest.getCount() : 10;

        // 创建分页对象，设置searchCount=true确保执行count查询
        Page<GoodsDO> page = new Page<>(pageNum, count, true);

        // 构建查询条件
        LambdaQueryWrapper<GoodsDO> queryWrapper = new LambdaQueryWrapper<>();

        // 只查询未删除的商品
        queryWrapper.eq(GoodsDO::getIsDeleted, 0);

        // 类型筛选，仅前端app调用时有效
        if (pageRequest instanceof GoodsPageRequest goodsPageRequest) {
            if (goodsPageRequest.getTypes() != null && !goodsPageRequest.getTypes().isEmpty()) {
                // 直接使用in条件，不使用嵌套
                queryWrapper.in(GoodsDO::getType, goodsPageRequest.getTypes());
            }
        }

        // 如果有关键词，则添加模糊查询条件——商品名称
        if (StringUtils.hasLength(pageRequest.getKeyword()) && !pageRequest.getKeyword().trim().isEmpty()) {
            queryWrapper.like(GoodsDO::getName, pageRequest.getKeyword());
        }

        // 按ID升序排序
        queryWrapper.orderByAsc(GoodsDO::getId);

        // 执行分页查询 - 使用baseMapper确保执行完整的分页查询
        Page<GoodsDO> resultPage = this.baseMapper.selectPage(page, queryWrapper);

        // 确保有记录返回
        if (resultPage.getRecords() == null || resultPage.getRecords().isEmpty()) {
            // 如果没有记录，手动执行一次查询
            List<GoodsDO> records = this.baseMapper.selectList(queryWrapper);
            if (records != null && !records.isEmpty()) {
                // 计算分页
                int start = (pageNum - 1) * count;
                int end = Math.min(start + count, records.size());
                if (start < records.size()) {
                    records = records.subList(start, end);
                    resultPage.setRecords(records);
                }
            }
        }

        // 转换为DTO并返回
        return goodsConverter.goodsPage2PageDTO(resultPage.getRecords(), resultPage.getTotal());
    }

    /**
     * 添加商品(后台商品管理)
     *
     * @param command 商品信息
     */
    @Override
    @Transactional
    @OperateLog(dateType = "商品", operateType = 1)
    public void addGoods(GoodsCommand command) {

        // 将请求体对象转换为商品实体
        GoodsDO goodsDO = goodsConverter.command2GoodsDO(command);

        // 保存商品信息
        boolean success = save(goodsDO);

        if (!success) {
            throw new BusinessException(ResultCodeEnum.FAIL);
        }
    }

    /**
     * 更新商品(后台商品管理)
     *
     * @param command 商品信息
     */
    @Override
    @Transactional
    @OperateLog(dateType = "商品", operateType = 2)
    public void updateGoods(GoodsCommand command) {
        // 检查商品ID是否存在
        if (!StringUtils.hasLength(command.getId())) {
            throw new BusinessException("商品ID不存在", ResultCodeEnum.PARAM_ERROR.getCode());
        }


        // 将请求体对象转换为商品实体
        GoodsDO goodsDO = goodsConverter.command2GoodsDO(command);

        // 更新商品信息
        boolean success = updateById(goodsDO);

        if (!success) {
            throw new BusinessException(ResultCodeEnum.GOODS_NOT_EXIST);
        }

    }

    /**
     * 删除商品(后台商品管理)
     *
     * @param goodsId 商品ID
     * @return 删除操作DTO
     */
    @Override
    @Transactional
    @OperateLog(dateType = "商品", operateType = 3)
    public DeleteGoodsOperateDTO deleteGoods(Long goodsId) {
        // 查询商品信息
        GoodsDO goodsDO = getById(goodsId);

        if (goodsDO == null) {
            throw new BusinessException(ResultCodeEnum.GOODS_NOT_EXIST);
        }

        // 逻辑删除商品
        LambdaUpdateWrapper<GoodsDO> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(GoodsDO::getId, goodsId)
                .set(GoodsDO::getIsDeleted, 1);

        boolean success = update(updateWrapper);

        if (!success) {
            throw new BusinessException(ResultCodeEnum.FAIL);
        }

        // 返回删除操作DTO
        return goodsConverter.goodsDO2DeleteGoodsDTO(goodsDO);
    }

    /**
     * 批量删除指定商品(后台商品管理)
     *
     * @param command 批量删除命令
     * @return 删除操作DTO列表
     */
    @Override
    @Transactional
    @OperateLog(dateType = "商品", operateType = 4)
    public List<DeleteGoodsOperateDTO> deleteGoodsSelected(BatchDeleteCommand command) {
        List<String> ids = command.getIds();

        if (ids == null || ids.isEmpty()) {
            return new ArrayList<>();
        }

        // 将字符串ID转换为Long类型
        List<Long> goodsIds = ids.stream()
                .map(Long::valueOf)
                .collect(Collectors.toList());

        // 查询要删除的商品信息
        List<GoodsDO> goodsList = listByIds(goodsIds);

        if (goodsList.isEmpty()) {
            return new ArrayList<>();
        }

        // 逻辑删除商品
        LambdaUpdateWrapper<GoodsDO> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.in(GoodsDO::getId, goodsIds)
                .set(GoodsDO::getIsDeleted, 1);

        boolean success = update(updateWrapper);

        if (!success) {
            throw new BusinessException(ResultCodeEnum.FAIL);
        }


        // 返回删除操作DTO列表
        return goodsConverter.goodsDOs2DeleteGoodsDTOs(goodsList);
    }

    /**
     * 更新商品上下架状态(后台商品管理)
     *
     * @param goodsId 商品ID
     * @param status  商品状态
     */
    @Override
    @Transactional
    @OperateLog(dateType = "商品", operateType = 5)
    public void updateGoodsStatus(Long goodsId, Integer status) {
        // 检查状态值是否合法
        if (status != 0 && status != 1) {
            throw new BusinessException("商品状态值无效，只能为0(下架)或1(上架)", ResultCodeEnum.PARAM_ERROR.getCode());
        }

        // 检查商品是否存在
        GoodsDO goodsDO = getById(goodsId);

        if (goodsDO == null) {
            throw new BusinessException(ResultCodeEnum.GOODS_NOT_EXIST);
        }

        // 更新商品状态
        LambdaUpdateWrapper<GoodsDO> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(GoodsDO::getId, goodsId)
                .set(GoodsDO::getStatus, status);

        boolean success = update(updateWrapper);

        if (!success) {
            throw new BusinessException(ResultCodeEnum.FAIL);
        }
    }
}
